<?php

/**
 * 商品订单处理
 */
namespace App\Service\Cloudh5Service;
use App\Service\Code\Normal;
use App\Service\BaseService;
use App\Model\PssModel\OrderSupplier;
use App\Model\PssModel\OrderSupplierGoods;
use App\Model\CommodityModel\SupplierCompany;
use App\Model\PssModel\Business;
use App\Service\OrderService\OrderInterfaceService\OrderAfterSaleVerify;
use App\Model\CommodityModel\CommodityArchives;

class SupplierOrderService extends BaseService
{
    /**
     * 获取待审核售后数量
     * 
     */
    public function getOrderAfterSaleCount() 
    {
        return OrderSupplier::instance()->getOrderAfterSaleCount();
    }
    
    /**
     * 获取售后订单列表
     * @param array $param
     */
    public function orderAfterSaleList(array $param = [])
    {
        $limit      = $param['limit'] ?? 15;
        $page       = $param['page'] ?? 0;
        
        $where[]= ['after_sale_status','=',1];
        $whereIn = [0];
        //搜索订单号
        if( isset($param['orderSn']) && !empty($param['orderSn']) ) {
            $order_sn = checkFields($param['orderSn']);
            $where[] = ['order_sn','=',$order_sn];
        }
        
        $order_fields = [
            'id as orderId',
            'order_sn as orderSn',
            'buyer_phone as buyerPhone',
            'company_id',
            'order_status as orderStatus',
            'after_verify_status as afterVerifyStatus',
            'real_total_money as realTotalMoney',
            'after_sale_remark as afterSaleremark',
        ];
        
        //待审核功能
        $query = OrderSupplier::instance()
        ->where($where)
        ->where('after_sale_status',1);
        
        //未处理
        if( isset($param['isAfterSaleChange']) && $param['isAfterSaleChange'] == 0 ) {
            $query->where('after_verify_status',0);
        } 
        
        //已处理
        if( isset($param['isAfterSaleChange']) && $param['isAfterSaleChange'] == 1 ) {
            $query->whereIn('after_verify_status',['1','2']);
        }
        
        $pageInfo = $query
        ->paginate($limit,$order_fields, 'page', $page,true)
        ->toArray();
        
        $list = $pageInfo['data'];
        
        //获取商品明细
        $orderIds       = array_column($list,'orderId');
        $orderGoodsList = OrderSupplierGoods::instance()->getSupplierOrderGoodsByOrderIds($orderIds);
        $orderGoodsListMap = array_group_by($orderGoodsList,'order_id');
        
        //供应商信息
        $supplierIds        = array_unique(array_column($list, 'company_id'));
        $supplierInfo       = SupplierCompany::instance()->getSupplierListByIds($supplierIds);
        $supplierInfoMap    = array_column($supplierInfo,null,'company_id');
        
        //开始组装数据
        foreach ($list as & $item )
        {
            $item['orderId']                = (string)$item['orderId'];
            $item['company_id']             = (string)$item['company_id'];
            
            //供应商
            $item['suppplierName']          = isset($supplierInfoMap[$item['company_id']])  ? $supplierInfoMap[$item['company_id']]['company_name'] : '供应商(仓库未审核)';
            
            //订单状态
            $item['orderStatusName']        = OrderSupplier::instance()->order_status[$item['orderStatus']];
            
            //订单审核状态
            $item['afterVerifyStatusName']  = OrderSupplier::instance()->after_verify_status[$item['afterVerifyStatus']];
            
            //是否进行售后处理
            $item['isAfterSaleChange']      = $item['afterVerifyStatus'] == 0 ? 0 : 1;
            //订单商品组
            $products = $orderGoodsListMap[$item['orderId']] ?? [];
            $goodsList = [];
           
            //商品总数
            $goodsTotal = 0;
            foreach ($products as $product)
            {
                $images     = \explode(",", $product['image']);
                $spec_num   = $product['spec_num'];
                $quantity   = $product['quantity'];
                $goods_type = $product['goods_type'];
                $price      = $product['price'];
                $goodsList[] = [
                    'goodsName'     => $product['goods_name'],
                    'image'         => current($images),
                    'num'           => (string)$quantity,
                    'price'         => (string)$price,
                    'priceTotal'    => bcmul((string)$quantity,(string)$price,2),
                    'specNum'       => (string)$spec_num,
                    'specName'      => (string)$product['spec_name'],
                    'goodsType'     => (string)$goods_type,
                    'goodsTypeName' => CommodityArchives::instance()->goods_types[$goods_type] ??'未定义'
                ];
                $goodsTotal += $quantity * $spec_num;
            }
            
            //商品总数
            $item['goodsTotal'] = $goodsTotal;
            
            //订单状态
            $item['products'] = $goodsList;
        }
        
        $pageInfo['data'] = $list;
        return Normal::returnCode(Normal::SUC,"请求成功",$pageInfo);
    }

    /**
     * 订单详情
     * @param string $orderId
     * @return mixed
     */
    public function OrderDetail(string $orderId)
    {
        $type = '';
        $orderInfo = OrderSupplier::instance()->info(['id' => $orderId],[
            'bid',
            'cd',
            'order_sn as orderSn',
            'buyer_realname as buyerRealName',
            'receive_name as receiveName',
            'recveive_phone as recveivePhone',
            'order_status as orderStatus',
            'after_verify_status as afterVerifyStatus',
            'pay_time as payTime',
            'deliver_money as deliverMoney',
            'discount_money as discountMoney',
            'real_total_money as realTotalMoney',
            'province',
            'city',
            'district',
            'receive_address as receiveAddress',
            'company_id'
        ]);
        if( empty($orderInfo) ) {
            return Normal::returnCode(Normal::FAIL,"没查到该订单");
        }
        $orderInfo['declareStatus']     = $orderInfo['orderStatus']==1 ? "等待清关" : "已清关";
        $orderInfo['orderStatus']       = OrderSupplier::instance()->order_status[$orderInfo['orderStatus']];
        $orderInfo['createTime']        = !empty($orderInfo['cd']) ? date('Y-m-d H:i:s',$orderInfo['cd']) :"" ;
        $orderInfo['payTime']           = !empty($orderInfo['payTime']) ? date('Y-m-d H:i:s',$orderInfo['payTime']) :"" ;
        $orderInfo['isAfterSaleChange'] = $orderInfo['afterVerifyStatus'] == 0 ? 0 : 1;
        
        //获取渠道商信息
        $binfo = Business::instance()->getUserInfoByBid($orderInfo['bid']);
        $orderInfo['merchantUserName']  = $binfo['name'];




        //获取商品明细
        $products = OrderSupplierGoods::instance()->getSupplierOrderGoodsByOrderId($orderId);
        if( empty($products) ) {
            return Normal::returnCode(Normal::FAIL,"获取订单数据失败");
        }

        //供应商信息
        $supplierInfo       = SupplierCompany::instance()->getSupplierListByIds([$orderInfo['company_id']]);
        $supplierInfoMap    = array_column($supplierInfo,null,'company_id');

        //供应商
        $orderInfo['suppplierName'] = isset($supplierInfoMap[$orderInfo['company_id']])  ? $supplierInfoMap[$orderInfo['company_id']]['company_name'] : '供应商(仓库未审核)';
        
        //商品总数
        $goodsTotal = 0;
        foreach ($products as & $value)
        {
            $tax_rate               = $value['taxRate'];
            $price                  = $value['price'];
            $quantity               = $value['quantity'];
            $spec_num               = $value['specNum'];
            
            if( $binfo['user_tag'] != 'jd' )
            {
                
                //税费
                $tax_all                = bcadd('1.000',$tax_rate,4);
                $noFeePrice             = bcdiv($price, $tax_all,2);
                $tax                    = bcsub($price, $noFeePrice,2);
                $value['tax']   	    = bcmul($tax,$quantity,2);
            
                //商品金额
                $price                  = bcsub($price,$tax,2);
                $value['notTaxPrice']   = bcmul($price,$quantity,2);
            
                //商品数量
                $value['count']         = (int)bcmul($spec_num,$quantity,2);
            }
            else
            {
                $price                  = $value['price'];
                $quantity               = $value['quantity'];
                $value['notTaxPrice']   = bcmul($spec_num,$quantity,2);
                $value['count']         = (int)bcmul($spec_num,$quantity);
            }
            
            //商品类型名称
            $value['goodsTypeName'] = CommodityArchives::instance()->goods_types[$value['goodsType']] ??'未定义';


            
            //商品圖片
            $images         = \explode(",", $value['image']);
            $value['image'] = current($images);
            $goodsTotal     += $quantity * $spec_num;
        }
        
        if( $binfo['user_tag'] != 'jd' ) 
        {
            //总税费
            $orderInfo['tax']           = number_format(array_sum(array_column($products,'tax')),2);
            //商品总金额
            $orderInfo['goodsMoney']    = number_format(array_sum(array_column($products,'notTaxPrice')),2);
            //商品总数量
            $orderInfo['totalCount']    = (int)$goodsTotal;
        }

        $orderInfo['orderGoods'] = $products;
        return Normal::returnCode(Normal::SUC,"订单详情获取成功",$orderInfo);
    }
    /**
     * 获取售后审核详情
     * @param array $param
     */
    public function orderAfterVerifyDetail($manager,$param)
    {
        if( empty($param['orderId']) ) {
            return Normal::returnCode(Normal::FAIL,"查询orderId不能为空");
        }
        
        $order_id = $param['orderId'];
        $orderInfo = OrderSupplier::instance()->info([
            ['id','=',$order_id]
        ]);
        
        if( empty($orderInfo) ) {
            return Normal::returnCode(Normal::FAIL,"订单未找到数据");
        }
        
        $after_sale_body = @json_decode($orderInfo['after_sale_body'],true);
        $afterSaleDescription = $after_sale_body['afterSaleDescription'] ?? '';
        $afterSaleAttachFiles = [];
        if( !empty($after_sale_body['afterSaleAttach']) ) {
            $afterSaleAttachFiles = @\explode(',', $after_sale_body['afterSaleAttach']);
        }
        

        //是否进行售后处理        
        $orderInfo = [
            'afterSaleReason'       => $orderInfo['after_sale_remark'],
            'afterSaleDescription'  => $afterSaleDescription,
            'afterSaleAttach'       => $afterSaleAttachFiles,
            'isAfterSaleChange'     => $orderInfo['after_verify_status'] == 0 ? 0 : 1,
            'realTotalMoney'        => $orderInfo['real_total_money'],
            'buyerPhone'            => $orderInfo['buyer_phone'],
            'buyerRealname'         => $orderInfo['buyer_realname'],
            'afterVerifyResult'     => OrderSupplier::instance()->after_verify_status[$orderInfo['after_verify_status']] ?? ''
        ];
        return Normal::returnCode(Normal::SUC,"售后详情获取成功",$orderInfo);
    }
    
    /**
     * 售后审核
     */
    public function orderAfterVerify($manager,$param)
    {
        $after_verify_remark = '';
        //审核状态
        if(!isset($param['afterVerifyStatus']) && empty($param['afterVerifyStatus'])) {
            return Normal::returnCode(Normal::FAIL,"审核状态不能为空");
        }
        if(!isset($param['orderId']) && empty($param['orderId'])) {
            return Normal::returnCode(Normal::FAIL,"订单ID不能为空");
        }
        if(isset($param['afterVerifyRemark'])) {
            $after_verify_remark = $param['afterVerifyRemark'];
        }
        $order_id = $param['orderId'];
        $after_verify_status = $param['afterVerifyStatus'];
        
        $orderSupplierInfo = OrderSupplier::instance()->info([
            ['id','=',$order_id]
        ]);
        
        if( empty($orderSupplierInfo) ) {
            return Normal::returnCode(Normal::FAIL,"订单未找到数据");
        }
        if( $orderSupplierInfo['after_sale_status'] != 1 ) {
            return Normal::returnCode(Normal::FAIL,"未申请售后的订单不能发生售后操作");
        }
        if( $orderSupplierInfo['after_verify_status'] == 1 ) {
            return Normal::returnCode(Normal::FAIL,"售后审核已通过的订单，不能再次进行操作审核");
        }
        if( $orderSupplierInfo['after_verify_status'] == 2 ) {
            return Normal::returnCode(Normal::FAIL,"售后审核已拒绝的订单，不能再次进行操作审核");
        }
        if( !in_array($after_verify_status, [1,2])) {
            return Normal::returnCode(Normal::FAIL,"afterVerifyStatus [1-审核通过，2-审核拒绝]");
        }
        if( $after_verify_status == 2 && empty($after_verify_remark) ) {
            return Normal::returnCode(Normal::FAIL,"审核拒绝必须填写原因");
        }
        
        $binfo = Business::instance()->getUserInfoByBid($orderSupplierInfo['bid']);
        $data = [
            "binfo" =>$binfo,
            "requestData" =>[
                'orderSn'               => $orderSupplierInfo['order_sn'],
                'orderNo'               => $orderSupplierInfo['supplier_csn'],
                'afterVerifyStatus'     => $after_verify_status,
                'afterVerifyRemark'     => $after_verify_remark,
                'sys_user_id'           => $manager["manager_id"],
                'sys_user_name'         => $manager["manager_name"],
            ],
        ];
        //调用售后审核
        return  OrderAfterSaleVerify::instance()->index($data);
    }


}